package com.zlzlib.librx;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;

import com.zlzlib.librx.listener.RxCancelListener;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;


/**
 * Created by zlz on 2019/8/20.
 */
public abstract class BaseProgressDialogHandler {

    public static final int SHOW_PROGRESS_DIALOG = 1;
    public static final int DISMISS_PROGRESS_DIALOG = 2;
    public static final int MESSAGE_PROGRESS_DIALOG = 3;

    protected Context context;
    private boolean cancelable;
    private RxCancelListener cancelListener;

    protected abstract Dialog getDialog();

    protected abstract void setDialogNull();

    protected abstract void setProgressMessage(String msg);

    public BaseProgressDialogHandler(Context context, RxCancelListener listener, boolean cancelable) {
        super();
        this.context = context;
        this.cancelListener = listener;
        this.cancelable = cancelable;
    }

    private void initProgressDialog() {
        if (getDialog() == null) {
            return;
        }
        getDialog().setCanceledOnTouchOutside(false);
        getDialog().setCancelable(cancelable);
        getDialog().setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                if (null != cancelListener) cancelListener.onCancelDisposable();
            }
        });
        if (!getDialog().isShowing()) {
            getDialog().show();
        }
    }

    private void dismissProgressDialog() {
        if (getDialog() != null) {
            getDialog().dismiss();
            setDialogNull();
        }
    }

    public void handleMessage(int what) {
        handleMessage(what, "");
    }

    public void handleMessage(final int what, final String msg) {
        AndroidSchedulers.mainThread().scheduleDirect(new Runnable() {
            @Override
            public void run() {
                switch (what) {
                    case SHOW_PROGRESS_DIALOG:
                        initProgressDialog();
                        break;
                    case DISMISS_PROGRESS_DIALOG:
                        dismissProgressDialog();
                        break;
                    case MESSAGE_PROGRESS_DIALOG:
                        setProgressMessage(msg);
                        break;
                }
            }
        });
    }

}